package com.pace.ribbon.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.Random;

public class StartCommand {
    private Logger logger = LoggerFactory.getLogger(StartCommand.class);

    public StartCommand(String[] args) {
        Boolean isServerPort = false;
        String serverPort = "";
        if (args != null) {
            for (String arg : args) {
                if(StringUtils.hasText(arg)&& arg.startsWith("--server.port")){
                    isServerPort=true;
                    serverPort=arg;
                    break;
                }
            }
        }
        // 如果没有指定端口，则随机生成一个可用的端口
        if(!isServerPort){
            int port = getAvailablePort();
            logger.info("cuurent server.port="+port);
            System.setProperty("server.port",String.valueOf(port));
        }else {
            logger.info("cuurent server.port="+serverPort.split("=")[1]);
            System.setProperty("server.port",serverPort.split("=")[1]);
        }

    }

    private int getAvailablePort() {
        int max = 65535;
        int min = 2000;
        Random random = new Random();
        int port =random.nextInt(max)%(max-min+1)+min;
        boolean using= NetUtil.isLoclePortUsing(port);
        if(using){
            return getAvailablePort();
        }else {
            return port;
        }
    }


}
